package com.example;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.example.utils.XssHttpServletRequestWraper;



/**
 * 自定义Filter
 * @author qxw
 *
 * Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter，并且我们可以自定义Filter。
 * 实现Filter接口，实现Filter方法
 * 添加@Configurationz 注解，将自定义Filter加入过滤链
 * 
 */

@Configuration
public class WebConfiguration {

	    @Bean
	    public RemoteIpFilter remoteIpFilter() {
	        return new RemoteIpFilter();
	    }
	     
	    @Bean
	    public FilterRegistrationBean testFilterRegistration() {
	 
	        FilterRegistrationBean registration = new FilterRegistrationBean();
	        registration.setFilter(new MyFilter());
	        registration.addUrlPatterns("/*");
	        registration.addInitParameter("paramName", "paramValue");
	        registration.setName("MyFilter");
	        registration.setOrder(1);
	        return registration;
	    }
	     
	    public class MyFilter implements Filter {
	    
	        @Override
			public void destroy() {
	            // TODO Auto-generated method stub
	        }
	 
	        @Override
			public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
	                throws IOException, ServletException {
	            // TODO Auto-generated method stub
	            HttpServletRequest request = (HttpServletRequest) srequest;
//	            System.out.println("请求地址=========url :"+request.getRequestURI());
//	            filterChain.doFilter(srequest, sresponse);
	            
	            filterChain.doFilter(new XssHttpServletRequestWraper((HttpServletRequest) srequest), sresponse);    
	        }
	 
	    
	        @Override
			public void init(FilterConfig arg0) throws ServletException {
	            // TODO Auto-generated method stub
	        }
	    }
}
